相关疑难解决方法(0)

MSVC中的ODR错误?

打印此程序1 1而不是1 2使用MSVC编译时(直到VS 2015).

f1.cpp:

#include <functional>

static std::function<int ()> helper() {
    struct F { int operator()() { return 1; } };
    return F();
}

std::function<int ()> f1() { return helper(); }
Run Code Online (Sandbox Code Playgroud)

f2.cpp:

#include <functional>

static std::function<int ()> helper() {
    struct F { int operator()() { return 2; } };
    return F();
}

std::function<int ()> f2() { return helper(); }
Run Code Online (Sandbox Code Playgroud)

main.cpp中:

#include <functional>
#include <iostream>

std::function<int ()> f1();
std::function<int ()> f2();

int main() {
    std::cout << …
Run Code Online (Sandbox Code Playgroud)

c++ one-definition-rule visual-c++

20
推荐指数
1
解决办法
325
查看次数

理解左值到右值转换的示例

我很难理解这段代码(C++ 14草案标准[conv.lval]中的一个例子)是如何调用未定义的行为的g(false).为什么constexpr让程序有效?

另外,"不访问y.n" 是什么意思?在两个调用中g()我们都返回n数据成员,为什么最后一行说它不访问它?

struct S { int n; };
auto f() {
    S x { 1 };
    constexpr S y { 2 };
    return [&](bool b) { return (b ? y : x).n; };
}
auto g = f();
int m = g(false); // undefined behavior due to access of x.n outside its
                  // lifetime
int n = g(true);  // OK, does not access y.n
Run Code Online (Sandbox Code Playgroud)

c++ language-lawyer lvalue-to-rvalue constexpr c++14

4
推荐指数
1
解决办法
612
查看次数