将所有出现的角色替换为另一个角色的有效方法是什么std::string?
标准说,取消引用空指针会导致未定义的行为.但是什么是"空指针"?在下面的代码中,我们称之为"空指针":
struct X
{
static X* get() { return reinterpret_cast<X*>(1); }
void f() { }
};
int main()
{
X* x = 0;
(*x).f(); // the null pointer? (1)
x = X::get();
(*x).f(); // the null pointer? (2)
x = reinterpret_cast<X*>( X::get() - X::get() );
(*x).f(); // the null pointer? (3)
(*(X*)0).f(); // I think that this the only null pointer here (4)
}
Run Code Online (Sandbox Code Playgroud)
我的想法是,只有在最后一种情况下才会取消引用空指针.我对吗?根据C++标准,编译时空指针和运行时之间是否存在差异?
如何允许在以下代码中使用私有析构函数删除对象?我已将实际程序缩减为以下示例,但它仍然可以编译并运行.
class SomeClass;
int main(int argc, char *argv[])
{
SomeClass* boo = 0; // in real program it will be valid pointer
delete boo; // how it can work?
return -1;
}
class SomeClass
{
private:
~SomeClass() {}; // ! private destructor !
};
Run Code Online (Sandbox Code Playgroud) 我正在尝试重载dereference运算符,但编译以下代码会导致错误'initializing' : cannot convert from 'X' to 'int':
struct X {
void f() {}
int operator*() const { return 5; }
};
int main()
{
X* x = new X;
int t = *x;
delete x;
return -898;
}
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
我的程序中有几个相同的字符串常量:
const char* Ok()
{
return "Ok";
}
int main()
{
const char* ok = "Ok";
}
Run Code Online (Sandbox Code Playgroud)
是否保证它们具有相同的地址,即我可以编写以下代码吗?我听说GNU C++优化了字符串,所以它们具有相同的地址,我可以在程序中使用该功能吗?
int main()
{
const char* ok = "Ok";
if ( ok == Ok() ) // is it ok?
;
}
Run Code Online (Sandbox Code Playgroud) 在下面的代码中:
template<typename T>
struct X {};
int main()
{
X<int()> x; // what is the type of T ?
}
Run Code Online (Sandbox Code Playgroud)
T的类型是什么?我在boost消息来源中看到了类似的东西.
我有以下代码似乎导致无限循环:
struct X
{
void my_func( int ) { std::cout << "Converted to int" << std::endl; }
};
struct X2 : X
{
void my_func( char value ) { my_func(value); }
};
Run Code Online (Sandbox Code Playgroud)
它有什么问题?
考虑一下我有以下几点struct:
struct IDirect3D
{
IDirect3D() : ref_count_(0) {}
unsigned long Release() { return --ref_count_; }
private:
long ref_count_;
~IDirect3D() {}
};
Run Code Online (Sandbox Code Playgroud)
我想shared_ptr在后面的代码(最小例子)中使用它:
int main()
{
boost::shared_ptr<IDirect3D> ptr;
IDirect3D* p = 0; // initialized somewhere
ptr.reset( p, boost::mem_fn( &IDirect3D::Release ) );
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这在大多数情况下都可以正常工作,但如果p等于,则可以使用0.我有以下要删除的删除器:
template<typename T, typename D>
inline void SafeDeleter( T*& p, D d )
{
if ( p != NULL ) {
(p->*d)();
p = NULL;
}
}
Run Code Online (Sandbox Code Playgroud)
但是下面的代码给出了很多错误(看起来像转储整个bind.hpp …
c++ ×8
algorithm ×1
bind ×1
boost ×1
constants ×1
dereference ×1
inheritance ×1
null-pointer ×1
shared-ptr ×1
stdstring ×1
str-replace ×1
templates ×1