相关疑难解决方法(0)

C++:空类对象的大小是多少?

我想知道一个空类的对象大小.它肯定不能是0字节,因为它应该可以像任何其他对象一样引用和指向它.但是,这样的对象有多大?

我用过这个小程序:

#include <iostream>
using namespace std;

class Empty {};

int main()
{
    Empty e;
    cerr << sizeof(e) << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我在Visual C++和Cygwin-g ++编译器上得到的输出是1个字节!这对我来说有点令人惊讶,因为我期望它的机器字大小(32位或4字节).

任何人都可以解释为什么 1字节的大小?为什么不是 4个字节?这是依赖于编译器还是机器?此外,有人可以给出一个更有说服力的理由,说明为什么空类对象的大小不是 0字节?

c++ class object

105
推荐指数
5
解决办法
6万
查看次数

如何不使用C头的声明污染全局命名空间?

我正在尝试用C++包装一个C库,使其成为一个现代的,高水平的,惯用的C++库.我想要做的是使C对象完全不透明和/或直接从C++代码中不可用,并用更高级别的替代品包装/替换它们.

我面临的问题很简单:我想只将C头包含在C++源代码中,这样C++头文件在包含时也不会包含C头文件的声明,也就是说,它不会污染C++头部.全局命名空间

但看起来头文件和源文件的正确分离似乎不允许我这样做.这是我的问题的一个非常模糊的版本,评论会告诉你其余的:


my_header.h:

typedef enum
{
    my_Consts_ALPHA = /* some special value */,
    my_Consts_BETA  = /* other special value */,
} my_Consts;

typedef struct
{
    // members...
} my_Type;

void
my_Type_method(my_Type *const,
               my_Enum);
Run Code Online (Sandbox Code Playgroud)

my_header.hpp:

namespace my
{
    enum class Consts; // <-- This header is missing the constant values of
                       //     this enum, because its values are defined by
                       //     the C header :( 

    class Type : public my_Type // <-- The super struct is coming from the
                                // …
Run Code Online (Sandbox Code Playgroud)

c++ namespaces header wrapper c++11

7
推荐指数
1
解决办法
1189
查看次数

提升compressed_pa​​ir和空对象的地址

AFAIK,boost :: compressed_pa​​ir应该确保第一个和第二个memebrs的地址是不同的,同时它可以实现压缩该对的魔力.它在这里说.看起来并非如此,并且它的行为在不同的编译器上是不同的.我正在使用boost v 1.47.我错过了什么?

struct E1 {};
struct E2 {};

boost::compressed_pair<E1, E2> diff_pair;
boost::compressed_pair<E1, E1> same_pair;

// clang++ and g++ 4.7 print the same address but VC2010 prints different addresses.
printf("different pairs = %p, %p\n", &diff_pair.first(), &diff_pair.second());

// clang++ and g++ 4.7 print different addresses but VC2010 prints the same address.
printf("different pairs = %p, %p\n", &same_pair.first(), &same_pair.second());
Run Code Online (Sandbox Code Playgroud)

c++ optimization boost

6
推荐指数
1
解决办法
1588
查看次数

标签 统计

c++ ×3

boost ×1

c++11 ×1

class ×1

header ×1

namespaces ×1

object ×1

optimization ×1

wrapper ×1