相关疑难解决方法(0)

C++静态const通过NULL指针访问

class Foo {
public:
 static const int kType = 42;
};

void Func() {
 Foo *bar = NULL;
 int x = bar->kType;
 putc(x, stderr);
}
Run Code Online (Sandbox Code Playgroud)

这是定义的行为吗?我阅读了C++标准但是找不到任何关于访问静态const值的内容......我已经检查了GCC 4.2,Clang ++和Visual Studio 2010生成的程序集,并且它们都没有执行NULL的解引用指针,但我想确定.

c++ static pointers

12
推荐指数
1
解决办法
1919
查看次数

移动语义如何与unique_ptr一起使用?

我正在尝试使用unique_ptr并编写一些简单的代码来检查它如何与移动语义一起工作.

#include <iostream>
#include <vector>
using namespace std;

class X
{
public:
    X(){}
    ~X() { cout << "Destructor X" << endl; }
    void Print() { cout << "X" << endl; }
};

int main()
{
    unique_ptr<X> ptr(new X());
    ptr->Print();

    vector<unique_ptr<X>> v;
    v.push_back(move(ptr));
    ptr->Print();
    v.front()->Print();

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出如下:

X
X
X
Destructor X
Run Code Online (Sandbox Code Playgroud)

我的期望是原始的unique_ptr ptr在push_back之后会失效.但Print()方法被调用就好了.这种行为会有什么解释?

c++ unique-ptr move-semantics c++11

3
推荐指数
2
解决办法
1120
查看次数

标签 统计

c++ ×2

c++11 ×1

move-semantics ×1

pointers ×1

static ×1

unique-ptr ×1